using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Msrp;


namespace Msrp.Network
{
    class ConnectionHandler
    {
        
        ConnectionHandler(Socket fSocket)
        {
            mSocket = fSocket;
        }

        ConnectionHandler(string fHostName, int fPort)
        {
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            mSocket.Connect(fHostName, fPort);
        }

        public void sendMessage(MessageChunk fChunk)
        {
           lock(mDictionaryLock)
           {
               ThreadSafeQueue<MessageChunk> q = null;
               mSendQueue.TryGetValue(fChunk.MessageId, q);
               if (q == null)
               {
                   q = new ThreadSafeQueue<MessageChunk>();
               }
               try
               {
                   ThreadSafeQueue<MessageChunk> q = mSendQueue[fChunk.MessageId];
               }
               catch (System.Exception e)
               {
               	
               }
               ThreadSafeQueue<MessageChunk> q = mSendQueue[fChunk.MessageId];
           }
        }

        public Socket getSocket()
        {
            return mSocket;
        }

        private class ThreadSafeQueue<T> : Queue<T>
        {
            public new void Clear()
            {
                lock (this)
                {
                    base.Clear();
                }                
            }
            public new void Enqueue(T item)
            {
                lock (this)
                {
                    base.Enqueue(item);
                }                
            }
            public new T Dequeue()
            {
                lock (this)
                {
                    return base.Dequeue();
                }
            }
            public int GetCount()
            {
                lock (this)
                {
                    return base.Count;
                }
            }
        };

        // ReaderWriterLock is bad in .NET 2, in .NET 3 there is ReaderWriterLockSlim
        // or just use some custom or 3rd party lock
        // For now we use simple lock
        private object mDictionaryLock = new object(); 

        private Dictionary<string, ThreadSafeQueue<MessageChunk>> mSendQueue = new Dictionary<string, ThreadSafeQueue<MessageChunk>>();
        private Socket mSocket;
    }
}
